package top.whysu.edevice.annotation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.whysu.edevice.constant.CodeConstant;
import top.whysu.edevice.exception.BusinessException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

/**
 * 数据字典校验
 */
public class DataDictionaryValidtor implements ConstraintValidator<DataDictionaryValidAnnotation, Object> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataDictionaryValidtor.class);
    Class<?>[] cls;
    boolean required;

    @Override
    public void initialize(DataDictionaryValidAnnotation annotation) {
        cls = annotation.target();
        required = annotation.required();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (!required && value == null) {
            return true;
        }
        if (cls.length > 0) {
            for (Class<?> cl : cls) {
                Field[] fields = cl.getFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    Object name;
                    try {
                        name = field.get(field.getName());
                        if (name.equals(value)) {
                            return true;
                        }
                    } catch (IllegalAccessException e) {
                        LOGGER.error("DataDictionaryVaildAnnotation校验出错", e);
                        throw new BusinessException(CodeConstant.Http.EXECUTE_FAIL, "校验出错" + e.getMessage());
                    }
                }
            }
        }
        return false;
    }


}
